package com.github.beihaifeiwu.myspring.http.feign;

import com.github.beihaifeiwu.myspring.core.SpringBeans;
import com.github.beihaifeiwu.myspring.utils.EX;
import feign.Feign;
import lombok.Data;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

/**
 * Created by liupin on 2017/9/5.
 */
@Data
public class FeignClientFactoryBean<T> implements FactoryBean<T>, InitializingBean {

    private Class<T> type;
    private String url;
    private String configurer;
    private boolean decode404;

    private Feign.Builder builder;

    @Override
    public void afterPropertiesSet() throws Exception {
        Assert.hasText(this.url, "url must be set");
        Assert.notNull(this.builder, "Bean of type Feign.Builder not exists");

        if (StringUtils.hasText(configurer)) {
            FeignBuilderConfigurer feignBuilderConfigurer = SpringBeans.getBean(configurer, FeignBuilderConfigurer.class)
                    .orElseThrow(() -> EX.wrap("Bean with type FeignBuilderConfigurer and name %s not exists", configurer));
            feignBuilderConfigurer.configure(builder);
        }

        if (decode404) {
            builder.decode404();
        }
    }

    @Override
    public T getObject() throws Exception {
        return builder.target(type, url);
    }

    @Override
    public Class<T> getObjectType() {
        return this.type;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

}